package Test;

import javax.swing.*;
import java.awt.event.*;

public class Menu extends JFrame implements ActionListener{
    protected JToolBar toolBar;
    protected JPopupMenu popupMenu;
    protected JMenu[] jMenus;

    public Menu(){

        this.setSize(100,50);
        this.toolBar = new JToolBar();
        this.getContentPane().add(this.toolBar,"North");

        JButton open = new JButton("打开");
        open.addActionListener(this);
        this.toolBar.add(open);
        JButton save = new JButton("保存");
        save.addActionListener(this);
        this.toolBar.add(save);

        this.addMenu();
        this.setVisible(true);
    }
    protected void addMenu(){
        String[] menu = {"文件","编辑"};
        String[][] menus = {{"新建","打开","保存","另存为","|","退出"},
                {"撤销","恢复","|","剪切","复制","粘贴"}};
        JMenuBar menuBar = new JMenuBar();
        this.setJMenuBar(menuBar);
        this.jMenus = new JMenu[menu.length];
        JMenuItem[][] menuItems = new JMenuItem[menus.length][];
        for (int i = 0; i < menus.length; i++) {
            this.jMenus[i] = new JMenu(menu[i]);
            menuBar.add(this.jMenus[i]);
            menuItems[i] = new JMenuItem[menus[i].length];
            for (int j = 0; j < menus[i].length; j++) {
                if(menus[i][j].equals("|")){
                    this.jMenus[i].addSeparator();
                }else {
                    menuItems[i][j] = new JMenuItem(menus[i][j]);
                    this.jMenus[i].add(menuItems[i][j]);
                    menuItems[i][j].addActionListener(this);
                }
            }
        }

        this.popupMenu = new JPopupMenu();
        String[] menu1 = {"剪切","复制","粘贴"};
        JMenuItem[] pop = new JMenuItem[menu1.length];
        for (int i = 0; i < pop.length; i++) {
            pop[i] = new JMenuItem(menu1[i]);
            this.popupMenu.add(pop[i]);
            pop[i].addActionListener(this);
        }
        pop[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_MASK));
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof JMenuItem){
            switch (e.getActionCommand()){
                case "退出":
                    if(JOptionPane.showConfirmDialog(this,"终止当前程序远行？","true",
                            JOptionPane.YES_NO_OPTION) == 0)
                        System.exit(0);
                case "剪切":
                case "复制":
                case "粘贴":
                    ;
            }
        }
    }
    public static void main(String[] args) {
        new Menu();
    }
}
